package com.xxx.reggie.controller;

import com.xxx.reggie.common.R;
import com.xxx.reggie.exception.SystemException;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String baseDir;   // "/upload" 配置的路径

    @RequestMapping("/upload")
    public R<String> upload(MultipartFile file){

        //获取存储上传图片的目录
        //获取类路径的根路径
        String rootClass = CommonController.class.getResource("/").getPath();

        //值为:D:\\Develop\\idea_Test\\reggie_take_out\\target\\classes

        //目标:将文件写入D:\\Develop\\idea_Test\\reggie_take_out\\target\\classes\\upload

        File dir = new File(baseDir);

        //判断upload是否存在
        if (!dir.exists()){
            //不存在就创建upload目录
            dir.mkdir();
        }

        //获取上传文件的名字(传入的初始文件名)
        String originalFilename = file.getOriginalFilename();

        //获取上传文件的扩展名
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));

        //定义生成一个唯一值的文件名
        String fileName = UUID.randomUUID() + extName;

        //将上传文件写入到磁盘
        try {
            file.transferTo(new File(dir,fileName));
        } catch (IOException e) {
            throw new SystemException("服务器写入磁盘文件失败",e);
        }
        return R.success(fileName);

    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){

        //获取存储上传图片的目录
        //获取类路径的根路径
        String filePath = baseDir +"/" +  name;

        //获取文件输入的字节流
        InputStream inputStream = null;

        try {
            inputStream = new FileInputStream(filePath);

            IOUtils.copy(inputStream,response.getOutputStream());
        } catch (IOException e) {
            throw new SystemException("获取文件失败",e);
        }

    }

}
